package com.mzx.javase.thread.concurrent;

import java.util.ArrayList;
import java.util.Random;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * 类描述：线程安全的集合类
 */
public class CopyOnWriteArrayListTest {
    public static void main(String[] args) {
        /**
         * 这个是线程安全的ArrayList，加强版读写分离，读无锁，写有锁，读写之间不阻塞
         * 写入时先加锁，copy一个容器副本、在添加新元素，最后替换引用
         * 使用方式与ArrayList无异
         */
        CopyOnWriteArrayList<String> arrayList = new CopyOnWriteArrayList<>();
//        copyOnWriteArrayList.add("我");
//        copyOnWriteArrayList.add("爱");
//        copyOnWriteArrayList.add("学习");
//        System.out.println("copyOnWriteArrayList：" + copyOnWriteArrayList);

//        ArrayList<String> arrayList = new ArrayList<>();
//        arrayList.add("我");
//        arrayList.add("爱");
//        arrayList.add("学习");
//        System.out.println("arrayList: " + arrayList);
        ExecutorService es = Executors.newFixedThreadPool(5);
        for (int i = 0; i < 5; i++) {
            es.submit(new Runnable() {
                @Override
                public void run() {
                    for (int j = 0; j < 10; j++) {
                        arrayList.add(Thread.currentThread().getName() + "..." + new Random().nextInt(1000));
                    }
                }
            });
        }
        //关闭线程池
        es.shutdown();
        //判断线程池中所有的线程是否执行完毕，true表示执行完毕,while(false)表示等待执行完毕
        while (!es.isTerminated()) {}
        System.out.println("元素个数：" + arrayList.size());
        for (String s : arrayList) {
            System.out.println(s);
        }
    }
}
